// 云函数入口文件
const cloud = require('wx-server-sdk')
cloud.init({ env: cloud.DYNAMIC_CURRENT_ENV })
const db = cloud.database()
const $ = db.command.aggregate
// 云函数入口函数
exports.main = async (event, context) => {
	const wxContext = cloud.getWXContext()
	switch (event.url) {
		case "getFollowPost": {
			const projectData = {
				topic: true,
				title: true,
				content: true,
				imgList: true,
				viewNum: true,
				createTime: true,
				userId: true
			}
			const res = await db.collection("post")
				.aggregate().lookup({
					from: "user",
					localField: "post.userId",
					foreignField: "user._id",
					as: "user"
				})
				.project({
					user: $.arrayElemAt(['$user', 0]),
					favor: true,
					...projectData
				})
				.project({
					isFans: $.in([event.userId, '$user.fans']),
					favorNum: $.size('$favor'),
					...projectData
				})
				.match({
					isFans: true,
					createTime: _.lt(event.lastTime || new Date().getTime())
				})
				.sort({ createTime: -1 })
				.limit(10)
				.end()
			return res
		}
	}
}